package com.dragon.www.haier.popupwindow;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.support.percent.PercentRelativeLayout;
import android.text.InputFilter;
import android.text.Spanned;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.dragon.www.haier.R;
import com.dragon.www.haier.activity.MainActivity;
import com.dragon.www.haier.database.DataHelper;
import com.dragon.www.haier.entity.Device;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by liqp on 2016/3/24.
 */
public class Setpopwindow extends BasePopupWindow implements View.OnClickListener, RadioGroup.OnCheckedChangeListener {

    private View mMenuView; //PopupWindow上面装载的View
    private ImageView imageBackSetting;
    private RadioGroup radioGroup_wind_mode;
    private ListView devices_list;
    private TextView devices_type_tx;
    private EditText et_devices_name;
    private EditText et_devices_id;
    private EditText et_devices_ip;
    private Button save;
    private Button delete;
    private Spinner devices_template_spin;
    private DeviceAdapter adapter;
    private ArrayAdapter<CharSequence> spinadapter;
    private PercentRelativeLayout devices_settingcontent;
    private int roomId;
    private String type = MainActivity.TYPE_LAMP;
    private int id;
    private int selectItemPosition = -1;

    public Setpopwindow(Context context) {
        super(context);
        mMenuView = LayoutInflater.from(context).inflate(R.layout.devices_setting, null);
        initView(mMenuView);
        initListener();

        //设置SignPopupWindow的View
        this.setContentView(mMenuView);
        //设置SignPopupWindow弹出窗体可点击
        this.setFocusable(true);
        this.setBackgroundDrawable(new BitmapDrawable());
        //防止虚拟软键盘被弹出菜单遮住
        this.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        this.setOutsideTouchable(false);

        devices_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Device deviceInfo = (Device) devices_list.getItemAtPosition(position);
                if (position == adapter.getData().size() - 1) {
                    et_devices_name.setText("");
                    et_devices_id.setText("");
                    et_devices_ip.setText("");
                    Setpopwindow.this.id = -1;
                    devices_settingcontent.setVisibility(View.VISIBLE);
                    selectItemPosition = -1;
                    adapter.notifyDataSetChanged();
                } else {
                    devices_settingcontent.setVisibility(View.VISIBLE);
                    Setpopwindow.this.id = deviceInfo.getDeviceId();
                    et_devices_name.setText(deviceInfo.getDeviceName());
                    et_devices_id.setText(Integer.toString(deviceInfo.getDeviceId()));
                    et_devices_ip.setText(deviceInfo.getIp());
                    if (deviceInfo.getTemplateName().equals("other_device")) {
                        devices_template_spin.setSelection(0, true);
                    } else if (deviceInfo.getTemplateName().equals("switch_device")) {
                        devices_template_spin.setSelection(1, true);
                    } else if (deviceInfo.getTemplateName().equals("air_container")) {
                        devices_template_spin.setSelection(2, true);
                    } else if (deviceInfo.getTemplateName().equals("curtain_device")) {
                        devices_template_spin.setSelection(3, true);
                    }
                    selectItemPosition = position;
                    adapter.notifyDataSetChanged();
                }
            }
        });

    }
    public void dataBaseHadRefreshed(){

    }
    public void showPopWindow(View view ,int xOffsetToView, int yOffsetToView) {
        super.showPopWindow(view, xOffsetToView, yOffsetToView);
    }

    public void initView(View contentView) {
        imageBackSetting = (ImageView) contentView.findViewById(R.id.image_back_setting);
        radioGroup_wind_mode = (RadioGroup) contentView.findViewById(R.id.radioGroup_wind_mode);
        adapter = new DeviceAdapter(context);
        devices_list = (ListView) contentView.findViewById(R.id.devices_list);
        devices_list.setAdapter(adapter);
        devices_settingcontent = (PercentRelativeLayout) contentView.findViewById(R.id.devices_settingcontent);
        et_devices_name = (EditText) contentView.findViewById(R.id.et_devices_name);
        et_devices_id = (EditText) contentView.findViewById(R.id.et_devices_id);
        et_devices_ip = (EditText) contentView.findViewById(R.id.et_devices_ip);
        devices_type_tx = (TextView) contentView.findViewById(R.id.devices_type_tx);
        save = (Button) contentView.findViewById(R.id.save);
        delete = (Button) contentView.findViewById(R.id.delete);
        devices_template_spin= (Spinner) contentView.findViewById(R.id.devices_template_spin);
        spinadapter=ArrayAdapter.createFromResource(
                context, R.array.devices_template_spin,
                android.R.layout.simple_spinner_dropdown_item);
        devices_template_spin.setAdapter(spinadapter);
        devices_template_spin.setSelection(1,true);
        et_devices_name.setFilters(new InputFilter[]{inputFilter});

    }

    public class DeviceAdapter extends BaseAdapter {

        public class DeviceViewHolder {
            public View v_select;
            public TextView tv_device;
        }

        private List<Device> devices = new ArrayList<>();
        private Context mcontext;

        public DeviceAdapter(Context context) {
            mcontext = context;
        }

        @Override
        public int getCount() {
            return devices.size();
        }

        @Override
        public Object getItem(int position) {
            return devices.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public void setData(List<Device> devices) {
            this.devices = devices;
            notifyDataSetChanged();
        }

        public List<Device> getData() {
            return devices;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final Device device = devices.get(position);
            DeviceViewHolder viewHolder;
            if (convertView == null) {
                viewHolder = new DeviceViewHolder();
                convertView = LayoutInflater.from(mcontext).inflate(R.layout.device_selected_item, parent, false);
                viewHolder.tv_device = (TextView) convertView.findViewById(R.id.tv_device);
                viewHolder.v_select = (View) convertView.findViewById(R.id.select_v);
                convertView.setTag(viewHolder);
            }else{
                viewHolder = (DeviceViewHolder) convertView.getTag();
            }
            if(selectItemPosition!=-1 && selectItemPosition == position){
                viewHolder.v_select.setVisibility(View.VISIBLE);
            }else{
                viewHolder.v_select.setVisibility(View.GONE);
            }
            viewHolder.tv_device.setText(device.getDeviceName());
            return convertView;
        }
    }

    public void setRoomId(int roomId) {
        this.roomId = roomId;
        refreshData(type);
    }

    private void refreshData(String type) {
        selectItemPosition = -1;
        devices_settingcontent.setVisibility(View.GONE);
        List<Device> devices = DataHelper.getInstance().getDevices(roomId, type);
        Device plus = new Device();
        plus.setDeviceName("+");
        devices.add(devices.size(), plus);
        adapter.setData(devices);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.setting_lamp:
                type = MainActivity.TYPE_LAMP;
                refreshData(type);
                devices_type_tx.setText("灯光");
                devices_template_spin.setSelection(1, true);
                break;
            case R.id.setting_air:
                type = MainActivity.TYPE_AIR;
                refreshData(type);
                devices_type_tx.setText("空调");
                devices_template_spin.setSelection(2,true);
                break;
            case R.id.setting_curtain:
                type = MainActivity.TYPE_CURTAIN;
                refreshData(type);
                devices_type_tx.setText("窗帘");
                devices_template_spin.setSelection(3,true);
                break;
            case R.id.setting_entanceguard:
                type = MainActivity.TYPE_ENTANCEGUARD;
                refreshData(type);
                devices_type_tx.setText("门禁");
                devices_template_spin.setSelection(1, true);
                break;
            case R.id.setting_humidifier:
                type = MainActivity.TYPE_HUMIDIFIER;
                refreshData(type);
                devices_type_tx.setText("加湿器");
                devices_template_spin.setSelection(1, true);
                break;
            case R.id.setting_plantwall:
                type = MainActivity.TYPE_PLANTWALL;
                refreshData(type);
                devices_type_tx.setText("植物墙");
                devices_template_spin.setSelection(1,true);
                break;
        }
    }

    public void initListener() {
        imageBackSetting.setOnClickListener(this);
        radioGroup_wind_mode.setOnCheckedChangeListener(this);
        save.setOnClickListener(this);
        delete.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (com.dragon.www.haier.util.Utils.isFastClick(500)) {
            return ;
        }
        String msg;
        switch (v.getId()) {
            case R.id.image_back_setting:
                dismiss();
                break;
            case R.id.save:
                String deviceName = et_devices_name.getText().toString().trim();
                String deviceId = et_devices_id.getText().toString().trim();
                String ip = et_devices_ip.getText().toString().trim();
                if(deviceName.equals("")){
                    Toast.makeText(context,"请输入设备名称",Toast.LENGTH_SHORT).show();
                    Animation shake= AnimationUtils.loadAnimation(context, R.anim.shake);
                    et_devices_name.startAnimation(shake);
                    return ;
                }
                if(deviceId.equals("")){
                    Toast.makeText(context,"请输入设备ID",Toast.LENGTH_SHORT).show();
                    Animation shake= AnimationUtils.loadAnimation(context, R.anim.shake);
                    et_devices_id.startAnimation(shake);
                    return ;
                }
//                if(ip.equals("")){
//                    Toast.makeText(contxt,"请输入ip值",Toast.LENGTH_SHORT).show();
//                    Animation shake= AnimationUtils.loadAnimation(contxt, R.anim.shake);
//                    et_devices_ip.startAnimation(shake);
//                    return ;
//                }
                String template = null;
                if(devices_template_spin.getSelectedItem().toString().equals("其它")){
                    template="other_device";
                }else if(devices_template_spin.getSelectedItem().toString().equals("开关")){
                    template="switch_device";
                }else if(devices_template_spin.getSelectedItem().toString().equals("空调")){
                    template="air_container";
                }else if(devices_template_spin.getSelectedItem().toString().equals("窗帘")){
                    template="curtain_device";
                }
                if (id == -1) {
                    int id = DataHelper.getInstance().getMaxId() + 1;
                    msg = DataHelper.getInstance().insertDevice(id, roomId, type, deviceName, deviceId, ip,template);
                } else {
                    msg = DataHelper.getInstance().updateDevice(roomId, id, deviceName, Integer.parseInt(deviceId), type, ip,template);
                }
                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
                refreshData(type);
                break;
            case R.id.delete:
                msg = DataHelper.getInstance().deleteDevice(roomId,id,type);
                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
                refreshData(type);
                break;
        }
    }
    InputFilter inputFilter = new InputFilter() {
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest,
                                   int dstart, int dend) {
            // TODO Auto-generated method stub
            try {
                //转换成中文字符集的长度
                int destLen = dest.toString().getBytes("utf-8").length;
                int sourceLen = source.toString().getBytes("utf-8").length;
                Log.e("filter", String.valueOf(destLen + sourceLen));
                if (destLen + sourceLen > 20) {  // 这里也不正确，考虑到复制一段文字，然后 粘贴一段已有文字的时候 会有问题，，要减去被粘贴那段文字的字节数
                    return "";
                }
                //如果按回退键
                if (source.length() < 1 && (dend - dstart >= 1)) {
                    return dest.subSequence(dstart, dend - 1);
                }
                return source;
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return source;
            }
        }
    };

}
